﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using ZhangLogSysV1d0;

namespace TmU220PrintHelperV2d0.Service
{
    /// <summary>
    /// 带超时的TcpClient，用于测试到打印机的连接
    /// </summary>
    public class TcpClientWithTimeoutV2d0
    {
        private object LockIsConnected = new object();
        /// <summary>
        /// 是否连接
        /// </summary>
        private bool _IsConnected ;
        public bool IsConnected
        {
            get
            {
                lock (LockIsConnected)
                {
                    return _IsConnected;
                }
            }
            set
            {
                lock (LockIsConnected)
                {
                    _IsConnected = value;
                }
            }
        }
        /// <summary>
        /// 超时信号量
        /// </summary>
        private ManualResetEvent TimeoutObject;
        public TcpClientWithTimeoutV2d0()
        {
            IsConnected = false;
            TimeoutObject = new ManualResetEvent(false);
        }
        /// <summary>
        /// 连接到tcp服务器
        /// </summary>
        /// <param name="serverip"></param>
        /// <param name="serverport"></param>
        /// <param name="timeoutMiliSecond"></param>
        /// <returns></returns>
        public  TcpClient TryConnect(string serverip, int serverport, int timeoutMiliSecond)
        {
            TimeoutObject.Reset();
            TcpClient currTcpClient = new TcpClient();
            IsConnected = false;
            try
            {
                currTcpClient.BeginConnect(serverip, serverport, new AsyncCallback(CallBackMethod), currTcpClient);
                //等待信号timeoutMiliSecond事件若干秒，
                if (TimeoutObject.WaitOne(timeoutMiliSecond, false))
                {
                    if (IsConnected)
                    {
                        return currTcpClient;
                    }
                }
                else
                {
                    //在指定时间内没有等到信号，则关闭tpclient，发出超时异常
                    IsConnected = false;
                    currTcpClient.Close();
                    currTcpClient = null;
                    //未连接发出异常
                    //throw new Exception("Socket Connect TimeOut Exception");
                }
            }
            catch (Exception ex)
            {
                IsConnected = false;
                currTcpClient.Close();
                //SimpleLoger.Instance.Error(ex);
            }
            return currTcpClient;
        }
        /// <summary>
        /// 异步连接的回调函数
        /// </summary>
        /// <param name="asyncresult"></param>
        private void CallBackMethod(IAsyncResult asyncresult)
        {
            try
            {
                IsConnected = false;
                TcpClient tmpTcpClient = asyncresult.AsyncState as TcpClient;
                if (tmpTcpClient.Client != null)
                {
                    tmpTcpClient.EndConnect(asyncresult);
                    IsConnected = true;
                }
            }
            catch (Exception ex)
            {
                IsConnected = false;
                SimpleLoger.Instance.Error(ex);
            }
            finally
            {
                //线程继续运行
                TimeoutObject.Set();
            }
        }
    }
}
